package com.atguigu.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.service.EduSubjectService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**
 * @Author hg
 * @CreatedTime 2020-10-05-11:48
 */
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    // 本类不能给spring管理，需要自己new，不能注入其他对象。
    // 不能操作数据库
    // 需要一个有参构造函数

    public EduSubjectService service;

    public SubjectExcelListener() {
    }

    public SubjectExcelListener(EduSubjectService service) {
        this.service = service;
    }

    // 读取excel内容
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData == null) {
            throw new GuliException(20001, "文件数据是空的");
        }

        // 每行有两个数据，一个是一级分类，一个是二级分类。
        EduSubject eduSubjectLevelOne = this.existLevelOneSubject(this.service, subjectData.getOneSubjectName());

        // 如果没有，那么表示不重复，添加新数据。
        if (eduSubjectLevelOne == null) {
            eduSubjectLevelOne = new EduSubject();
            eduSubjectLevelOne.setParentId(0L);
            eduSubjectLevelOne.setTitle(subjectData.getOneSubjectName());
            this.service.save(eduSubjectLevelOne);
        }

        // 获取一级分类对应的二级分类id
        Long id = eduSubjectLevelOne.getId();

        EduSubject eduSubjectLevelTwo = this.existLevelTwoSubject(this.service, subjectData.getOneSubjectName(), id);

        if (eduSubjectLevelTwo == null) {
            eduSubjectLevelTwo = new EduSubject();
            eduSubjectLevelTwo.setParentId(id);
            eduSubjectLevelTwo.setTitle(subjectData.getTwoSubjectName());
            this.service.save(eduSubjectLevelTwo);
        }
    }

    // 一级分类不能重复添加，这里判断当前行是否有一级分类。
    private EduSubject existLevelOneSubject(EduSubjectService service, String name) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", "0");
        return service.getOne(wrapper);
    }

    // 二级分类不能重复添加
    private EduSubject existLevelTwoSubject(EduSubjectService service, String name, Long pid) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", pid);
        return service.getOne(wrapper);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
